import { _decorator, Prefab, Node, instantiate, NodePool, Vec3, director } from "cc";

export class PoolManager {
    private static _dictPool: any = {}

    /**
     * 根据预设从对象池中获取对应节点
     */
    public static getNode(prefab: Prefab, parent?: Node):Node {
        let name = prefab.name;
        //@ts-ignore
        if (!prefab.position) {
            //@ts-ignore
            name = prefab.data.name;
        }

        let node = null;
        if (this._dictPool.hasOwnProperty(name)) {
            //已有对应的对象池
            let pool = this._dictPool[name];
            if (pool.size() > 0) {
                node = pool.get();
            } else {
                node = instantiate(prefab);
            }
        } else {
            //没有对应对象池，创建他！
            let pool = new NodePool();
            this._dictPool[name] = pool;

            node = instantiate(prefab);
        }

        if(parent) node.parent = parent;
        else director.getScene().addChild(node)
        node.position = Vec3.ZERO;
        node.active = true;

        return node;
    }

    /**
     * 将对应节点放回对象池中
     */
    public static putNode(node: Node) {
        if (!node) {
            return;
        }
        let name = node.name;
        let pool = null;
        if (this._dictPool.hasOwnProperty(name)) {
            //已有对应的对象池
            pool = this._dictPool[name];
        } else {
            //没有对应对象池，创建他！
            pool = new NodePool();
            this._dictPool[name] = pool;
        }
        node.active = false;
        pool.put(node);
    }

    /**
     * 根据名称，清除对应对象池
     */
    public static clearPool(name: string) {
        if (this._dictPool.hasOwnProperty(name)) {
            let pool = this._dictPool[name];
            pool.clear();
        }
    }
}
